<template>
	<view class="content">
		<image class="logo" src="/static/logo.jpg"></image>
		<view class="text-area">
			<!-- <text class="title">{{title}}</text> -->
		</view>
		
		<view class="colStart">
			<uni-forms style="margin-top: 20px;" ref="formRef" :value="formData" :rules="rules" err-show-type="toast">
				<uni-forms-item name="userName" required>
					<uni-easyinput :inputBorder="true" :focus="focusUserName" @blur="focusUserName = false"
						class="input-box sxf-easyinput" placeholder="请输入名字" v-model="formData.userName" trim="both" 
						:maxlength="16" />
				</uni-forms-item>
				<uni-forms-item name="phone" required>
					<uni-easyinput :inputBorder="true" :focus="focusPhone" @blur="focusPhone = false"
						class="input-box sxf-easyinput" placeholder="请输入手机号码" v-model="formData.phone" trim="both" 
						:maxlength="11" type="tel"/>
				</uni-forms-item>
				<uni-forms-item name="code" required>
					<view class="colCenter">
						<view class="rowAround" style="align-items: center;">
							<view class="colCenter">
								<uni-easyinput :inputBorder="true" :focus="focusCode" @blur="focusCode = false"
									class="input-box sxf-easyinput" placeholder="请输入短信验证码" v-model="formData.code" trim="both" 
									:maxlength="6" type="number" :clearable="false" />
							</view>
							<button class="uni-btn marginLeft" :type="disableSmsCode ? 'default' : 'primary'" size="default" 
								style="width: 150px; font-size: 14px;" @click="onGetCode" :disabled="disableSmsCode">{{ smsCodeBtnText }}</button>
						</view>
					</view>
				</uni-forms-item>
				
				<view class="colCenter" style="margin-top: 100px;">
					<view class="rowBetween">
						<!-- <button class="marginRight" style="flex: 1;" @click="onBack">返回</button> -->
						<button class="marginLeft" style="flex: 3;" type="warn" @click="onRegist">注册</button>
					</view>
				</view>
			</uni-forms>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { computed, ref } from "vue";
	import { onLoad } from "@dcloudio/uni-app";
	import StrUtil from "@/utils/StrUtils.js";
	import { gzhShare } from "@/utils/WxGzhUtil";
	import { useStore } from "vuex";
	
	const store = useStore();
	
	const sxf_theater = uniCloud.importObject("sxf-theater");
	
	let formData = ref({
		userName: "",
		phone: "",
		code: ""
	});
	
	let formRef = ref(null);
	
	const rules = ref({
		userName: {
			rules: [
				{
					required: true,
					errorMessage: '请输入名字',
				},
				{
					minLength: 2,
					maxLength: 16,
					errorMessage: '名字长度在 {minLength} 到 {maxLength} 个字符',
				},
				{
					validateFunction: (rule, value, data, callback) => {
						// console.log(value);
						if (/^1\d{10}$/.test(value) || /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)) {
							callback('名字不能是：手机号或邮箱')
						};
						if (/^\d+$/.test(value)) {
							callback('名字不能为纯数字')
						};
						return true
					}
				}
			],
			label: "名字"
		},
		phone: {
			rules: [
				{
					required: true,
					errorMessage: '请输入手机号码',
				},
				{
					minLength: 11,
					maxLength: 11,
					errorMessage: '手机号码长度是 {minLength} 位数字',
				},
				{
					validateFunction: (rule, value, data, callback) => {
						// console.log(value);
						if (/^1\d{10}$/.test(value)) {
							return true;
						} else {
							callback('手机号码格式不正确');
						}
					}
				}
			],
			label: "手机号码"
		},
		code: {
			rules: [
				{
					required: true,
					errorMessage: '请输入短信验证码',
				},
				{
					minLength: 6,
					maxLength: 6,
					errorMessage: '短信验证码长度是 {minLength} 个字符',
				},
				{
					validateFunction: (rule, value, data, callback) => {
						// console.log(value);
						if (/^\d{6}$/.test(value)) {
							return true;
						} else {
							callback('短信验证码不能为非数字');
						}
					}
				}
			],
			label: "短信验证码"
		},
	});
	
	let focusUserName = ref(false);
	let focusPhone = ref(false);
	let focusCode = ref(false);
	
	let disableSmsCode = ref(false);
	let smsCodeBtnText = ref("获取验证码");
	let smsCodeTimer = null;
	let timerCount = ref(0);
	const maxCount = 30;
	
	onLoad(async(option) => {
		console.log("option", option);
		
		gzhShare({
			isShowMenu: false, // 隐藏菜单
			shareInfo: {}
		});
	});
	
	const startSmsCodeTimer = () => {
		stopSmsCodeTimer();
		// 冻结
		disableSmsCode.value = true;
		timerCount.value = maxCount;
		// 开启解冻倒计时
		smsCodeTimer = setInterval(() => {
			timerCount.value -= 1;
			if (timerCount.value <= 0) {
				stopSmsCodeTimer();
			} else {
				smsCodeBtnText.value = "获取验证码" + "(" + timerCount.value + ")";
			}
		}, 1000);
	};
	
	const stopSmsCodeTimer = () => {
		if (smsCodeTimer != null) {
			clearInterval(smsCodeTimer);
			smsCodeTimer = null;
		}
		smsCodeBtnText.value = "获取验证码";
		timerCount.value = 0;
		disableSmsCode.value = false;
	};
	
	const onGetCode = async () => {
		// 获取验证码
		if (!StrUtil.isEmpty(formData.value.phone) && 
		    formData.value.phone.length == 11 && 
			(/^1\d{10}$/.test(formData.value.phone))) {
			// 开始倒计时处理按钮冻结状态
			startSmsCodeTimer(); 
			
			// 获取验证码
			const res = await sxf_theater.sendRegistCodeSms({ 
				userId: getApp().globalData.curUserId, 
				phone: formData.value.phone,
			});
			// const res = { code: 0, msg: "发送成功" };
			// console.log(res);
			if (res.code != 0) {
				// 发送失败
				console.error(res.msg)
				uni.showToast({
					title: "发送失败，请稍候再试！",
					icon: "none"
				});
			} else {
				// 发送成功
				uni.showToast({
					title: "已发送验证码"
				});
				focusCode.value = true;
			}
		} else {
			uni.showToast({
				title: "手机号码格式不正确！",
				icon: "none"
			});
			focusPhone.value = true;
		}
	};
	
	const onRegist = () => {
		// 注册
		formRef.value.validate().then(async (res) => {
			// 验证验证码
			const checkRes = await sxf_theater.checkRegistCode({ 
				phone: formData.value.phone, 
				code: formData.value.code
			});
			if (checkRes.checkResult) {
				// 验证成功
				const openId = getApp().globalData.curOpenId;
				if (StrUtil.isEmpty(openId)) {
					// 没有openId，不进行注册
					console.warn("没有openId，不进行注册！！")
					uni.showToast({
						title: "用户数据不合法",
						icon: "none"
					});
					return;
				} else {
					// 进行注册
					const registRes = await sxf_theater.registUser({
						userName: formData.value.userName,
						phone: formData.value.phone,
						code: formData.value.code,
						openId: getApp().globalData.curOpenId,
						userId: getApp().globalData.curUserId,
						shareUserId: getApp().globalData.shareUserId
					});
					if (registRes.code == 0) {
						uni.showToast({
							title: "注册成功！"
						});
						
						// 更新用户信息
						getApp().globalData.curUserInfo = registRes.userInfo;
						store.commit("setUserInfo", registRes.userInfo);
						
						// 返回上一页面
						setTimeout(() => {
							uni.navigateBack();
						}, 1000);
					} else {
						uni.showToast({
							title: registRes.msg ? registRes.msg : "注册失败",
							icon: "none"
						});
					}
				}
			} else {
				// 验证失败
				uni.showToast({
					title: checkRes.msg ? checkRes.msg : "验证失败",
					icon: "none"
				});
				focusCode.value = true;
			}
		}).catch((errors) => {
			let key = errors[0].key;
			key = "focus" + key.replace(key[0], key[0].toUpperCase());
			// console.log("key:", key);
			if (key === "focusUserName") {
				focusUserName.value = true;
			} else if (key === "focusPhone") {
				focusPhone.value = true;
			} else if (key === "focusCode") {
				focusCode.value = true;
			}
		});
	};
	
	const onBack = () => {
		// 返回
		uni.navigateBack();
	};
</script>

<style lang="scss" scoped>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	
	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 30rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 20rpx;
	}
	
	.text-area {
		display: flex;
		justify-content: center;
	}
	
	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	
	.desc {
		font-size: 26rpx;
		color: #8f8f94;
	}
	
	.sxf-easyinput input {
		padding-right: 0; /* 去除清除图标占用的空间 */
	}
</style>